package com.surpassun.emall.controller;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.surpassun.emall.model.Category;
import com.surpassun.emall.model.City;
import com.surpassun.emall.model.Product;
import com.surpassun.emall.service.CategoryService;
import com.surpassun.emall.service.CityService;
import com.surpassun.emall.service.ProductService;
import com.surpassun.emall.util.CacheUtil;
import com.surpassun.emall.util.Constants;

@Controller
@RequestMapping("/")
public class HomeController {
	
	@Inject
	CategoryService categoryService;
	
	@Inject
	CityService cityService;
	
	@Inject
	ProductService productService;
	
	@RequestMapping
	public String view(HttpServletRequest request, Model model) {
		//add application cache
		Map<String, Object> cache = CacheUtil.getApplicationCache();
		//get categories
		@SuppressWarnings("unchecked")
		List<Category> categories = (List<Category>) cache.get(Constants.ATTR_CATEGORIES);
		model.addAttribute(Constants.ATTR_CATEGORIES, categories);
		
		//get popular categories
		List<Category> popularCategories = categoryService.getPopularCategories();
		model.addAttribute(Constants.ATTR_POPULAR_CATEGORIES, popularCategories);
		
		//get popular cities
		List<City> popularCities = cityService.getPopularCities();
		model.addAttribute(Constants.ATTR_POPULAR_CITIES, popularCities);
		
		return "home";
	}
	
	@RequestMapping("/productByCategory")
	public String getStoreByCategory(HttpServletRequest request, @RequestParam(required=true) long categoryId, Model model) {
		List<Product> products = productService.getProductsByCategory(categoryId);
		model.addAttribute(Constants.ATTR_PRODUCTS, products);
		return "productList";
	}
	
	@RequestMapping("/productByCity")
	public String getStoreByCity(HttpServletRequest request, @RequestParam(required=true) long cityId, Model model) {
		List<Product> products = productService.getProductsByCity(cityId);
		model.addAttribute(Constants.ATTR_PRODUCTS, products);
		return "productList";
	}
}
